﻿using AutoMapper;
using ProjectManageSystemApi.DbEntity;
using ProjectManageSystemApi.Models;
using ProjectManageSystemApi.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProjectManageSystemApi.Services
{
    public class SystemServices : ServicesBase, ISystemServices
    {
        public SystemServices(IFreeSql fsql, IMapper mapper) : base(fsql, mapper) { }
        public SysUpgradeDto CheckUpdate(string appName)
        {
            var tmp = _fsql.Select<SysUpgrade>().Where(p => p.State == 1).WhereIf(!string.IsNullOrWhiteSpace(appName),x => x.AppName.Equals(appName)).OrderByDescending(p => p.VersionInsideNo).ToOne();
            return _mapper.Map<SysUpgradeDto>(tmp);
        }

        public bool Create(SysUpgradeDto sysUpgrade)
        {
            try
            {
                var data = _mapper.Map<SysUpgrade>(sysUpgrade);
                data.CreateTime = DateTime.Now;
                data.State = 1;
                uint id = (uint)_fsql.Insert(data).ExecuteIdentity();
                if (id <= 0)
                {
                    throw new DbTranException("增加 sys_upgrade 表失败");
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool Del(uint id)
        {
            return _fsql.Update<SysUpgrade>().Set(p => p.State, 2).Where(x => x.Id == id).ExecuteAffrows() > 0;
        }

        public bool ExistByAppNameAndInsideNo(string appName, int versionInsideNo)
        {
            return _fsql.Select<SysUpgrade>().Where(p => p.AppName == appName && p.VersionInsideNo == versionInsideNo && p.State == 1).ToList().Count > 0;
        }

        public bool ExistId(uint id)
        {
            return _fsql.Select<SysUpgrade>().Where(p => p.Id == id).ToList().Count > 0;
        }

        public PageVo<IEnumerable<SysUpgradeDto>> GetAll(PageBo<SysUpgradeParams> pageBo)
        {
            var datas = _fsql.Select<SysUpgrade>().Where(p => p.State == 1).OrderByDescending(p=>p.CreateTime);
            if (!string.IsNullOrWhiteSpace(pageBo.Param.AppName))
            {
                datas = datas.Where(d => d.AppName.Contains(pageBo.Param.AppName));
            }
            if (!string.IsNullOrWhiteSpace(pageBo.Param.VersionNo))
            {
                datas = datas.Where(d => d.VersionMainNo.Contains(pageBo.Param.VersionNo));
            }
            var total = datas.Count();
            datas = datas.Page(pageBo.Page, pageBo.Size);

            var data = new Models.PageVo<IEnumerable<SysUpgradeDto>>
            {
                Page = pageBo.Page,
                Size = pageBo.Size,
                Datas = _mapper.Map<List<SysUpgradeDto>>(datas.ToList()),
                Total = total
            };
            return data;
        }
    }
}
